<template>
  <div class="item-group-container">
    <!-- 顶部操作区域 -->
    <div class="top-section">
      <transition name="search-slide">
        <div class="search-area" v-show="showSearchArea">
          <div class="search-status" v-if="hasSearchConditions">
            <el-tag size="small" type="info">
              当前搜索条件: {{ getSearchConditionsText() }}
            </el-tag>
          </div>
          <el-input v-model="searchForm.Code" placeholder="请输入编码" class="search-input" clearable
            @keyup.enter="handleSearch" />

          <el-select v-model="searchForm.Type" placeholder="请选择类型" class="search-input" clearable
            @change="handleSearch">

            <el-option v-for="item in groupTypes" :key="item.id" :label="item.groupTypeName"
                            :value="item.id" />
          </el-select>
          <el-select v-model="searchForm.Status" multiple placeholder="请选择状态" class="search-input" clearable
            @change="handleSearch">

            <el-option v-for="item in processRoutes" :key="item.Id" :label="item.RouteName"
                            :value="item.Id" />
          </el-select>
          <el-select v-model="searchForm.LineName" placeholder="请选择群组类型" class="search-input" clearable
            @change="handleSearch">

            <el-option v-for="item in lineIdList" :key="item.linesId" :label="item.lineName"
                            :value="item.linesId" />
          </el-select>
          <el-button type="primary" @click="handleSearch" class="search-btn">
            <el-icon>
              <Search />
            </el-icon>
            搜索
          </el-button>
          <el-button @click="clearSearch" class="clear-btn">
            <el-icon>
              <Close />
            </el-icon>
            清空
          </el-button>
          <el-dropdown @command="loadSearchHistory" v-if="searchHistory.length > 0">
            <el-button class="history-btn">
              <el-icon>
                <Clock />
              </el-icon>
              历史
              <el-icon class="el-icon--right">
                <ArrowDown />
              </el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item v-for="(item, index) in searchHistory" :key="index" :command="item">
                  {{ getSearchHistoryText(item) }}
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </transition>
      <div class="utility-icons">
        <el-tooltip :content="showSearchArea ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-icon class="icon-btn" @click="toggleSearchArea" :class="{ 'active': showSearchArea }">
            <Search />
          </el-icon>
        </el-tooltip>
        <el-tooltip content="刷新" placement="top">
          <el-icon class="icon-btn" @click="refreshData">
            <Refresh />
          </el-icon>
        </el-tooltip>
        <el-tooltip content="全屏" placement="top">
          <el-icon class="icon-btn" @click="toggleFullscreen">
            <Expand />
          </el-icon>
        </el-tooltip>
        <el-tooltip content="设置" placement="top">
          <el-icon class="icon-btn">
            <Setting />
          </el-icon>
        </el-tooltip>
        <el-tooltip content="关闭" placement="top">
          <el-icon class="icon-btn">
            <Close />
          </el-icon>
        </el-tooltip>
      </div>
    </div>
    <div class="gantt-container" ref="containerRef">
      <!-- 今天标记线 -->
      <div class="today-marker" :style="{ left: todayPosition +'%'}">
        <div class="today-label">{{ todayLabel }}</div>
      </div>
      <g-gantt-chart :chart-start="ganttStart" :chart-end="ganttEnd" precision="day" date-format="YYYY-MM-DD HH:mm:ss"
        bar-start="planDateS" bar-end="planDateE" :push-on-overlap="false" :no-overlap="true" :grid="true"
        :row-height="40" label-column-title="产线 产线编号" label-column-width="300px" style="width: 87vw;" color-scheme="creamy"
        class="full-width-gantt">
        <template #upper-timeunit="{ date }">
          <!-- <el-date-picker v-model="applicationDate" type="date" placeholder="选择时间" value-format="YYYY-MM-DD"
            :clearable="false" style="width: 130px;" /> -->
        </template>
        <template #timeunit="{ label, value }">
          <el-text style="text-align: left;width: 100%;">{{ moment(value).format('MM.DD') }}</el-text>
        </template>
        <template #label-column-row="{ label }">
          <el-tooltip class="box-item" effect="dark" :content="`产线:${label.lineName}，产线编号：${label.lineCode}`"
            placement="right" :popper-options="getPopperOptions">
            <div class="label-column-content">
              <el-text style="width: 270px;" :truncated="true">
                {{ label.lineName }} | {{ label.lineCode }}
              </el-text>
            </div>
          </el-tooltip>
        </template>

        <g-gantt-row v-for="(item, index) in tableData" :key="item.id" :label="item" :bars="[item.rowBarList]">
          <!-- 确保 bars 是数组 -->

          <template #bar-label="{ bar }">
            <el-tooltip class="box-item" effect="dark" :content="`${bar.ganttBarConfig?.label}`" raw-content
              placement="top" :popper-options="getPopperOptions">
              <el-text style="width: 100%;text-align: center"> {{ bar.ganttBarConfig?.label }}</el-text>
            </el-tooltip>
          </template>
        </g-gantt-row>
      </g-gantt-chart>
    </div>
  </div>
</template>

<script lang="ts" setup>
const containerRef = ref<HTMLElement | null>(null)
import { ref, reactive, onMounted, onUnmounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Download,
  Delete,
  Grid,
  Search,
  Refresh,
  Expand,
  Setting,
  Close,
  Sort,
  Clock,
  ArrowDown
} from '@element-plus/icons-vue'
import Maxios from '@/Http/MesHelp'
import { log } from 'vxe-pc-ui'
import moment from 'moment'


// ==================== 响应式数据定义 ====================
const loading = ref(false) // 表格加载状态
interface ProcessData {
  id: number,
  lineName: string,
  lineCode: string,
  qty: number,
  completedQty: number,
  type: string,
  rowBarList: {
    planDateS: string | Date; // 允许字符串或Date类型
    planDateE: string | Date; // 允许字符串或Date类型
    ganttBarConfig: {
      id: number,
      label: string,
      hasHandles: false,
      immobile: true,
      style: {
        background: string,
        borderRadius: string,
        color: string
      }
    }
  }
}
interface GroupType {
    id: string
    groupTypeName: string
}
interface Lines {
    linesId: number,
    lineCode: string,
    lineName: string
}
interface ProcessRoute {
    Id: string
    RouteName: string
}
const tableData = ref<ProcessData[]>([]) // 明确指定类型为 ProcessData 数组
const groupTypes = ref<GroupType[]>([{ id: '正常', groupTypeName: '正常' }, { id: '委外', groupTypeName: '委外' }, { id: '维修', groupTypeName: '维修' }, { id: '自建工单', groupTypeName: '自建工单' }]) // 群组类型数据
const processRoutes = ref<ProcessRoute[]>([{ Id: '初始化', RouteName: '初始化' }, { Id: '备料中', RouteName: '备料中' }, { Id: '已开工', RouteName: '已开工' }, { Id: '暂停', RouteName: '暂停' }, { Id: '完工', RouteName: '完工' }, { Id: '结案', RouteName: '结案' }])
const lineIdList = ref<Lines[]>([])
const getLineIdList = async () => {
    const res = await Maxios.get('/api/Process/GetsLines')
    if (res.data.code === 200) {
        lineIdList.value = res.data.data
    }
}
const dialogVisible = ref(false) // 对话框显示状态
const dialogTitle = ref('新增物料群组') // 对话框标题
const isEdit = ref(false) // 是否为编辑模式

const showSearchArea = ref(true) // 搜索区域显示状态
const searchHistory = ref<Array<{ ItemCode: string, ItemName: string[], Type: string, LineName: string }>>([]) // 搜索历史记录

// 添加今天相关的响应式变量
const todayPosition = ref(0) // 今天在甘特图中的水平位置百分比
const todayLabel = ref('') // 今天的标签文本

// ==================== 表单数据定义 ====================
// 搜索表单数据
const searchForm = reactive({
  Code: '', // 群组编码搜索条件
  Type: '', // 群组名称搜索条件
  Status: ["备料中"] as string[], // 群组类型搜索条件
  LineName: ''
})
// API基础URL配置
const API_BASE_URL = '/api'  // 后端控制器路由为 api/[controller]/[action]

// 获取物料群组列表数据
const getItemGroups = async () => {
  loading.value = true
  try {
    // 调用后端API获取物料群组数据（包含分页参数）
    const response = await Maxios.get(`${API_BASE_URL}/Process/GetGatt`, {
      params: {
        Code: searchForm.Code || null,
        Status: searchForm.Status || null,
        Type: searchForm.Type || null,
        LineName: searchForm.LineName || null,
      },
  paramsSerializer: {
    indexes: null // 禁用索引格式，使用 Status=value1&Status=value2 格式
  }
    })

    if (response.data.code === 200) {
      const result = response.data.data // 获取分页结果对象
      // 确保日期格式正确
      result.forEach((item: ProcessData) => {
        if (item.rowBarList) {
          // 将字符串日期转换为Date对象（如果需要）
          if (typeof item.rowBarList.planDateS === 'string') {
            item.rowBarList.planDateS = new Date(item.rowBarList.planDateS);
          }
          if (typeof item.rowBarList.planDateE === 'string') {
            item.rowBarList.planDateE = new Date(item.rowBarList.planDateE);
          }
        }
      });
      console.log('API返回数据:', result)
      tableData.value = result
      // 直接使用后端返回的数据（已包含类型名称和工艺路线名称）
    }
  }
  catch (error) {
    console.error('获取群组失败:', error)
    console.log('API调用详情:', {
      url: `${API_BASE_URL}/ItemGroup/ItemGroupQuery`,
      fullUrl: `http://localhost:5293${API_BASE_URL}/ItemGroup/ItemGroupQuery`,
      params: {
        Code: searchForm.Code || null,
        Status: searchForm.Status || null,
        Type: searchForm.Type || null,
        LineName: searchForm.LineName || null,
        ItemMsg: null,
      }
    })


  } finally {
    loading.value = false
  }
}
// 执行搜索操作
const handleSearch = () => {

  // 保存搜索历史记录
  if (hasSearchConditions.value) {
    const currentSearch = {
      ItemCode: searchForm.Code,
      ItemName: searchForm.Status,
      Type: searchForm.Type,
      LineName: searchForm.LineName
    }

    // 避免重复添加相同的搜索条件
    const exists = searchHistory.value.some(item =>
      item.ItemCode === currentSearch.ItemCode &&
      JSON.stringify(item.ItemName) === JSON.stringify(currentSearch.ItemName)  &&
      item.Type === currentSearch.Type &&
      item.LineName === currentSearch.LineName
    )

    if (!exists) {
      searchHistory.value.unshift(currentSearch) // 添加到历史记录开头
      // 只保留最近10条搜索历史
      if (searchHistory.value.length > 10) {
        searchHistory.value = searchHistory.value.slice(0, 10)
      }
    }
  }

  getItemGroups() // 执行搜索并获取数据（后端会处理分页和过滤）
}

// 切换搜索区域的显示/隐藏状态
const toggleSearchArea = () => {
  showSearchArea.value = !showSearchArea.value // 切换显示状态
}

// 刷新数据列表
const refreshData = () => {
  getItemGroups() // 重新获取数据
  ElMessage.success('数据已刷新')
}

// 切换浏览器全屏模式
const toggleFullscreen = () => {
  if (!document.fullscreenElement) {
    document.documentElement.requestFullscreen() // 进入全屏
  } else {
    document.exitFullscreen() // 退出全屏
  }
}
// 清空搜索条件
const clearSearch = () => {
  searchForm.Code = '' // 清空编码搜索条件
  searchForm.Status = [] as string[] // 清空名称搜索条件
  searchForm.Type = '' // 清空类型搜索条件
  searchForm.LineName = '' // 清空类型搜索条件
  handleSearch() // 执行搜索（此时会搜索所有数据）
  ElMessage.success('搜索条件已清空')
}

// ==================== 计算属性 ====================
// 计算属性：检查是否有搜索条件
const hasSearchConditions = computed(() => {
  return searchForm.Code || (searchForm.Status && searchForm.Status.length > 0) || searchForm.Type || searchForm.LineName
})


// 获取当前搜索条件的文本描述
const getSearchConditionsText = () => {
  const conditions = []
  if (searchForm.Code) conditions.push(`编码: ${searchForm.Code}`)
if (searchForm.Status && searchForm.Status.length > 0) {
  conditions.push(`状态: ${searchForm.Status.join(', ')}`)
}  if (searchForm.Type) {
    // const groupType = groupTypes.value.find(type => type.id === searchForm.RoutingTypeId)
    conditions.push(`类型: ${searchForm.Type}`)
  }
  if (searchForm.LineName) {
    // const groupType = groupTypes.value.find(type => type.id === searchForm.RoutingTypeId)
    conditions.push(`产线: ${searchForm.LineName}`)
  }
  return conditions.join(', ') // 用逗号连接所有条件
}

// 获取搜索历史项的文本描述
const getSearchHistoryText = (item: { ItemCode: string, ItemName: string[], Type: string, LineName: string }) => {
  const conditions = []
  if (item.ItemCode) conditions.push(`编码: ${item.ItemCode}`)
if (item.ItemName && item.ItemName.length > 0) {
  conditions.push(`状态: ${item.ItemName.join(', ')}`)
}
  if (item.Type) {
    // const groupType = groupTypes.value.find(type => type.id === item.ItemTypeId)
    conditions.push(`类型: ${item.Type}`)
  }
  if (item.LineName) {
    // const groupType = groupTypes.value.find(type => type.id === item.ItemTypeId)
    conditions.push(`类型: ${item.LineName}`)
  }
  return conditions.join(', ') || '空搜索' // 如果没有条件则显示"空搜索"
}

// 加载搜索历史记录到搜索表单
const loadSearchHistory = (item: { ItemCode: string, ItemName: string[], Type: string, LineName: string }) => {
  searchForm.Code = item.ItemCode // 填充编码搜索条件
  searchForm.Status = item.ItemName || [] // 填充名称搜索条件
  searchForm.Type = item.Type // 填充类型搜索条件
  searchForm.LineName = item.LineName // 填充类型搜索条件 
  handleSearch() // 执行搜索
  ElMessage.success('已加载搜索历史')
}

// 处理键盘快捷键事件
const handleKeydown = (event: KeyboardEvent) => {
  // Ctrl + F 切换搜索区域显示/隐藏
  if (event.ctrlKey && event.key === 'f') {
    event.preventDefault() // 阻止默认行为
    toggleSearchArea()
  }
  // F5 刷新数据
  if (event.key === 'F5') {
    event.preventDefault() // 阻止默认行为
    refreshData()
  }
}

// 获取tooltip的popper选项
const getPopperOptions = computed(() => {
  return {
    modifiers: [
      {
        name: 'preventOverflow',
        options: {
          boundary: containerRef.value, // 使用容器作为边界
          padding: 8
        }
      },
      {
        name: 'flip',
        options: {
          padding: 8
        }
      },
      {
        name: 'computeStyles',
        options: {
          adaptive: true,
          gpuAcceleration: false
        }
      }
    ]
  }
})

// ==================== 生命周期钩子 ====================
// 组件挂载时初始化数据
onMounted(() => {
  getItemGroups() // 获取物料群组列表数据
getLineIdList()
  // 添加键盘事件监听器
  document.addEventListener('keydown', handleKeydown)
  // 初始化今天标记
  initTodayMarker()
  if (containerRef.value) {
    console.log("容器已挂载");
    // 计算百分比
    const percentage = getGanttRangePercentage();
    console.log(`当前日期在今年的百分比: ${percentage}%`);
    // 定位滚动条（假设容器宽度为scrollWidth）
    const container = containerRef.value;
    if (container.scrollWidth) {
      // 滚动到对应百分比位置
      container.scrollLeft = (container.scrollWidth * percentage) / 100;
      
    }
  }
})

// 组件卸载时清理事件监听器
onUnmounted(() => {
  // clearInterval(timer)
  document.removeEventListener('keydown', handleKeydown) // 移除键盘事件监听器

})
//#region 数据
// 当选选择的时间
const ganttStart = new Date('2025-01-01 00:00:00');
const ganttEnd = new Date('2025-12-12 23:59:59');

function getGanttRangePercentage() {

  const today = new Date();
  today.setHours(0, 0, 0, 0);

  // 边界处理
  if (today < ganttStart) return 0;
  if (today > ganttEnd) return 100;

  // 精确计算毫秒差转换为天数
  const totalMs = ganttEnd.getTime() - ganttStart.getTime();
  const passedMs = today.getTime() - ganttStart.getTime();

  // 计算百分比（保留4位小数提高精度）
  return parseFloat(((passedMs / totalMs) * 100).toFixed(4));
}

// 初始化今天的位置和标签
const initTodayMarker = () => {
  console.log(getGanttRangePercentage());

  todayPosition.value =(containerRef.value?.scrollWidth||0 * getGanttRangePercentage()) /21.05
  todayLabel.value = moment().format('今天 YYYY-MM-DD')
  console.log(todayPosition.value);

}

// 会议室申请列表：
const meetingRoomRequestStatusList = ref([{
  "id": 1,
  "roomName": "1#310会议室",
  "capacity": 30,
  "rowBarList": [{
    "startTime": "2025-05-12 11:00:00",
    "endTime": "2025-05-13 12:00:00",
    "ganttBarConfig": {
      "id": 2,
      "label": "XXX",
      // 是否有操作条
      "hasHandles": false,
      // 是否可移动：true 为不可一定
      "immobile": true,
      "style": {
        "background": "#2CABE3",
        "borderRadius": "5px",
        "color": "black"
      }
    }
  }]
}, {
  "id": 2,
  "roomName": "1#303-会议室",
  "capacity": 8,
  "rowBarList": [{
    "startTime": "2025-02-12 09:30:00",
    "endTime": "2025-05-12 11:00:00",
    "ganttBarConfig": {
      "id": 6,
      "label": "XXXXX",
      "hasHandles": false,
      "immobile": true,
      "style": {
        "background": "#2CABE3",
        "borderRadius": "5px",
        "color": "black"
      }
    }
  }]
}, {
  "id": 3,
  "roomName": "1#3F录播室",
  "rowBarList": [{
    "startTime": "2025-04-12 07:00:00",
    "endTime": "2025-07-12 08:00:00",
    "ganttBarConfig": {
      "id": 3,
      "label": "XXX",
      "hasHandles": false,
      "immobile": true,
      "style": {
        "background": "#2CABE3",
        "borderRadius": "5px",
        "color": "black"
      }
    }
  }]
},
{
  "id": 4,
  "roomName": "1#2F实操室",
  "capacity": 12,
  "rowBarList": [{
    "startTime": "2025-01-12 07:00:00",
    "endTime": "2025-09-12 08:00:00",
    "ganttBarConfig": {
      "id": 4,
      "label": "XXX",
      "hasHandles": false,
      "immobile": true,
      "style": {
        "background": "#2CABE3",
        "borderRadius": "5px",
        "color": "black"
      }
    }
  }]
}])
//#endregion
</script>
<style scoped>
/* 添加今天标记的样式 */
.today-marker {
  position: absolute;
  top: 0;
  height: 100%;
  width: 2px;
  background-color: #c80408;
  z-index: 1000;
  pointer-events: none;
  /* 新增：基于甘特图容器的滚动偏移修正位置 */
  transform: translateX(-1px);
  /* 修正线宽导致的偏移 */
}

.today-label {
  position: absolute;
  top: -20px;
  left: 0;
  background-color: #ff4d4f;
  color: white;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  transform: translateX(-50%);
  white-space: nowrap;
}

.item-group-container {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.top-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.search-area {
  flex: 1;
  display: flex;
  gap: 10px;
  align-items: center;
  flex-wrap: wrap;
}

.search-status {
  width: 100%;
  margin-bottom: 10px;
}

.search-input {
  width: 200px;
}

.search-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.clear-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.history-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 5px;
}

.delete-btn {
  background-color: #f56c6c;
  border-color: #f56c6c;
}

.delete-btn:hover {
  background-color: #f78989;
  border-color: #f78989;
}

.utility-icons {
  display: flex;
  gap: 15px;
}

.icon-btn {
  font-size: 18px;
  color: #606266;
  cursor: pointer;
  padding: 5px;
  border-radius: 4px;
  transition: all 0.3s;
}

.icon-btn:hover {
  color: #409eff;
  background-color: #f0f9ff;
}

.icon-btn.active {
  color: #409eff;
  background-color: #f0f9ff;
}

.table-section {
  background: white;
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.data-table {
  width: 100%;
}

.search-icon {
  margin-left: 5px;
  font-size: 12px;
  color: #909399;
}

.sort-icon {
  margin-left: 3px;
  font-size: 12px;
  color: #909399;
}

.action-link {
  color: #409eff;
  text-decoration: none;
  margin: 0 5px;
}

.delete-link {
  color: #f56c6c;
}

.pagination-section {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-top: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.data-summary {
  color: #606266;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
}

.pagination-controls .el-pagination {
  margin: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 搜索区域动画 */
.search-slide-enter-active,
.search-slide-leave-active {
  transition: all 0.3s ease;
}

.search-slide-enter-from,
.search-slide-leave-to {
  opacity: 0;
  transform: translateY(-10px);
  max-height: 0;
}

.search-slide-enter-to,
.search-slide-leave-from {
  opacity: 1;
  transform: translateY(0);
  max-height: 100px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .top-section {
    flex-direction: column;
    align-items: stretch;
  }

  .search-input {
    width: 100%;
  }

  .action-buttons {
    justify-content: center;
  }

  .utility-icons {
    justify-content: center;
  }

  .pagination-section {
    flex-direction: column;
    gap: 15px;
  }
}

/* 确保tooltip内的文本容器随滚动固定 */
.label-column-content {
  position: sticky;
  left: 0;

  z-index: 20;
  /* 保证在其他内容上方 */
  width: 100%;
  box-sizing: border-box;
}

.g-gantt-row-label,
.g-gantt-row-label-container {
  position: static !important;
  left: 0 !important;
  background: white !important;
  /* 避免滚动时内容重叠 */
  z-index: 10 !important;
  transition: none !important;
}

/* 确保甘特图容器样式正确 */
.gantt-container {
  width: 100%;
  overflow-x: auto;
  padding-bottom: 10px;
  position: relative;
  /* 关键：添加相对定位 */
  box-sizing: border-box;
  /* 新增：避免内边距影响定位 */
  padding-left: 0;
  padding-right: 0;
}

.full-width-gantt {
  min-width: 14000px;
  width: 100%;
}

.g-gantt-row-label {
  width: 100px !important;
  min-width: 100px !important;
  max-width: 100px !important;
  box-sizing: border-box !important;
  overflow: hidden !important;
  text-overflow: ellipsis !important;
}

/* 优化文本显示样式 */
.el-tooltip .el-text {
  display: inline-block;
  vertical-align: middle;
  white-space: nowrap;
  /* 防止文本换行 */
}
</style>